import os

filename = "student.txt"


# 保存
def save(student):
    try:
        students_txt = open(filename, "a", encoding="utf-8")
    except Exception as e:
        students_txt = open(filename, "w", encoding="utf-8")
    for info in student:
        students_txt.write(str(info) + "\n")
    students_txt.close()


def insert():
    students = []
    mark = True
    while mark:
        id = input("请输入ID(如1001)：")
        if not id:
            break
        name = input("请输入名字：")
        try:
            english = int(input("请输入英语成绩："))
            python = int(input("请输入python成绩："))
            c = int(input("请输入C语言成绩："))
        except Exception as e:
            print("输入无效，不是整型数值")
        student = {"id": id, "name": name, "english": english, "python": python, "c": c}
        students.append(student)
        inputMark = input("是否继续添加?(y/n):")
        if inputMark == 'y':
            mark = True
        else:
            mark = False
    save(students)
    print("学生信息录入完毕")


# 删除
def delete():
    mark = True
    while mark:
        studentId = input("请输入要删除的学生ID:")
        if studentId is not "":
            if os.path.exists(filename):
                with open(filename, 'r') as rfile:
                    student_old = rfile.readlines()
            else:
                student_old = []
        ifdel = False
        if student_old:
            with open(filename, 'w') as wfile:
                d = {}
                for list in student_old:
                    d = dict(eval(list))
                    if d['id'] != studentId:
                        wfile.write(str(d) + "\n")
                    else:
                        ifdel = True
                if ifdel:
                    print("ID为 %s 的学生信息已经删除" % studentId)
                else:
                    print("ID为 %s 的学生信息未找到" % studentId)
        else:
            print("无学生信息")
            break
    show()
    inputMark = input("是否继续删除?(y/n):")
    if inputMark == 'y':
        mark = True
    else:
        mark = False


# 修改
def modify():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding="utf-8") as rfile:
            student_old = rfile.readlines()
    else:
        return
    studentid = input("请输入要修改的学生ID:")
    with open(filename, 'w', encoding="utf-8") as wfile:
        for student in student_old:
            d = dict(eval(student))
            if d['id'] == studentid:
                print("找到了这名学生，可以开始修改他的信息:")
                while True:
                    try:
                        d['name'] = input("请输入姓名:")
                        d['english'] = int(input("请输入英文成绩:"))
                        d['python'] = int(input("请输入python成绩:"))
                        d['c'] = int(input("请输入c语言成绩:"))
                    except:
                        print("你输入有误，请重新输入")
                    else:
                        break
                student = str(d)
                wfile.write(student + "\n")
                print("修改成功")
            else:
                wfile.write(student)
    mark = input("是否继续修改其他学生信息(y/n):")
    if mark == 'y':
        modify()


# 查询
def search():
    mark = True
    student_query = []
    while mark:
        id = ""
        name = ""
        if os.path.exists(filename):
            mode = input("按照ID输入1;按照姓名输入2:")
            if mode == '1':
                id = input("请输入学生ID:")
            elif mode == '2':
                name = input("请输入学生姓名:")
            else:
                print("你的输入有误，请重新输入")
                search()
            with open(filename, 'r', encoding="utf-8") as file:
                student = file.readlines()
                for list in student:
                    d = dict(eval(list))
                    if id is not "":
                        if d['id'] == id:
                            student_query.append(d)
                    elif name is not "":
                        if d['name'] == name:
                            student_query.append(d)
            show_student(student_query)
            student_query.clear()
            inputMark = input("是否继续查询?(y/n):")
            if inputMark == 'y':
                mark = True
            else:
                mark = False
        else:
            print("暂无保存数据信息")
            return


# 展示数据
def show_student(student_list):
    if not student_list:
        print("无数据信息")
        return
    format_title = "{:^6}{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^10}"
    print(format_title.format("ID", "名字", "英语成绩", "python成绩", "c语言成绩", "总成绩"))
    format_data = "{:^6}{:^12}\t{:^10}\t{:^10}\t{:^14}\t{:^10}"
    for info in student_list:
        print(
            format_data.format(info.get("id"), info.get("name"), info.get("english"), info.get("python"), info.get("c"),
                               str(info.get("english") + info.get("python") + info.get("c")).center(12)))


# 统计总数
def total():
    if os.path.exists(filename):
        with open(filename, 'r', encoding="utf-8") as rfile:
            student_old = rfile.readlines()
            if student_old:
                print("一共有 %d 名学生！" % len(student_old))
            else:
                print("还没有录入学生信息！")
    else:
        print("暂未保存信息。。。。")


# 所有学生信息
def show():
    student_new = []
    if os.path.exists(filename):
        with open(filename, 'r', encoding="utf-8") as file:
            student_old = file.readlines()
            if student_old:
                for list in student_old:
                    student_new.append(eval(list))
            if student_new:
                show_student(student_new)
    else:
        print("暂未保存信息。。。。")

# 排序
def sort():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding="utf-8") as file:
            student_old = file.readlines()
            student_new = []
        for list in student_old:
            d = dict(eval(list))
            student_new.append(d)
    else:
        return
    ascORdesc = input("请选择(0.升序 1.降序)?:")
    if ascORdesc == "0":
        ascORdesc = False
    elif ascORdesc == "1":
        ascORdesc = True
    else:
        print("输入有误，请重新输入")
        sort()
    mode = input("请选择排序方式(1.按英语排序;2.按python排序;3.按C语言排序;4.按总成绩排序)")
    if mode == '1':
        student_new.sort(key=lambda x: x['english'], reverse=ascORdesc)
    elif mode == '2':
        student_new.sort(key=lambda x: x['python'], reverse=ascORdesc)
    elif mode == '3':
        student_new.sort(key=lambda x: x['c'], reverse=ascORdesc)
    elif mode == '4':
        student_new.sort(key=lambda x: x['english'] + x['python'] + x['c'], reverse=ascORdesc)
    else:
        print("你的输入有误，请重新输入")
        sort()
    show_student(student_new)
